package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: YHL
 * @time: 2021/2/21 20:47
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryBrandService categoryBrandService;
    @Override
    public List<CategoryDTO> queryCategoryByParent(Long pid) {
        List<Category> categories = this.query().eq("parent_id", pid).list();
//        把查询到的分类的entity集合转换为dto集合
        List<CategoryDTO> categoryDTOS = CategoryDTO.convertEntityList(categories);

        return categoryDTOS;
    }

    @Override
    public CategoryDTO queryCategoryById(Long id) {
        return new CategoryDTO(this.getById(id));
    }

    @Override
    public List<CategoryDTO> listCategoryByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            throw new LyException(400,"分类id集合不能为空");
        }
        return CategoryDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    public List<CategoryDTO> listCategoryByBrand(Long bid) {
//      根据品牌id在中间表中查询出所有的对应的分类和品牌的对象，并获取到品牌的id的集合
//       select * from tb_category_brand where brand_id = #{bid}
        List<Long> categoryIds = this.categoryBrandService.query()
                .eq("brand_id", bid)
                .list()
                .stream()
                .map(CategoryBrand::getCategoryId)
                .collect(Collectors.toList());

//        根据分类的id集合查询对应的分类信息
        return CategoryDTO.convertEntityList(this.listByIds(categoryIds));
    }
}
